/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package LogParser;

import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 *
 * @author Иван
 */
public final class XMLParser {

    private Document doc = null;
    private StringBuffer buffer;

    public XMLParser(String fileName) {
        try {
            buffer = new StringBuffer(0);
            doc = parserXML(new File(fileName));

            buildDOMTree(doc);
        } catch (Exception error) {
            error.printStackTrace();
        }
    }

    private void buildDOMTree(Node node) {
        int type = node.getNodeType();
        switch (type) {

            case Node.DOCUMENT_NODE: {
                buffer.append("<?xml version=\"1.0\" ?>");
                buildDOMTree(((Document) node).getDocumentElement());
                break;
            }
            case Node.ELEMENT_NODE: {
                buffer.append("<");
                buffer.append(node.getNodeName());

                NamedNodeMap attrs = node.getAttributes();
                for (int i = 0; i < attrs.getLength(); i++) {
                    buildDOMTree(attrs.item(i));
                }

                buffer.append(">");

                if (node.hasChildNodes()) {
                    NodeList children = node.getChildNodes();
                    for (int i = 0; i < children.getLength(); i++) {
                        buildDOMTree(children.item(i));
                    }
                }

                buffer.append("</");
                buffer.append(node.getNodeName());
                buffer.append('>');

                break;
            }
            case Node.ATTRIBUTE_NODE: {
                buffer.append(" ").append(node.getNodeName()).append("=\"").append(((Attr) node).getValue()).append("\"");
                break;
            }

            case Node.TEXT_NODE: {
                buffer.append(node.getNodeValue());
                break;
            }
        }
    }

    public String getDOMTree() {
        return buffer.toString();
    }

    public Document parserXML(File file) throws SAXException, IOException, ParserConfigurationException {
        return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
    }
}
